<template>
  <div class="model-logs-container">
    <el-card class="filter-card">
      <div class="filter-area">
        <el-form :model="queryParams" ref="queryForm" :inline="true" class="filter-form">
          <!-- 时间范围筛选 -->
          <el-form-item label="调用时间范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              :shortcuts="dateShortcuts"
              @change="handleDateRangeChange"
            />
          </el-form-item>

          <!-- 模型名称筛选 -->
          <el-form-item label="模型名称">
            <el-select
              v-model="queryParams.model_name"
              placeholder="选择模型"
              clearable
              style="width: 200px"
            >
              <el-option v-for="model in modelOptions" :key="model" :label="model" :value="model" />
            </el-select>
          </el-form-item>

          <!-- 用户ID筛选 -->
          <el-form-item label="用户ID">
            <el-input
              v-model="queryParams.user_id"
              placeholder="请输入用户ID"
              clearable
              style="width: 200px"
            />
          </el-form-item>

          <!-- 操作按钮 -->
          <el-form-item>
            <el-button type="primary" @click="handleQuery">
              <el-icon><Search /></el-icon> 查询
            </el-button>
            <el-button @click="resetQuery">
              <el-icon><RefreshRight /></el-icon> 重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 统计信息卡片 -->
    <el-row :gutter="20" class="statistics-row">
      <el-col :span="6">
        <el-card class="statistic-card">
          <div class="statistic-item">
            <div class="statistic-icon total-calls">
              <el-icon><Connection /></el-icon>
            </div>
            <div class="statistic-info">
              <div class="statistic-title">总调用次数</div>
              <div class="statistic-value">{{ statistics.total_calls || 0 }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistic-card">
          <div class="statistic-item">
            <div class="statistic-icon total-tokens">
              <el-icon><DocumentChecked /></el-icon>
            </div>
            <div class="statistic-info">
              <div class="statistic-title">总Token数</div>
              <div class="statistic-value">{{ formatNumber(statistics.total_tokens) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistic-card">
          <div class="statistic-item">
            <div class="statistic-icon avg-tokens">
              <el-icon><Histogram /></el-icon>
            </div>
            <div class="statistic-info">
              <div class="statistic-title">平均Token数</div>
              <div class="statistic-value">{{ formatNumber(statistics.avg_tokens, 1) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistic-card">
          <div class="statistic-item">
            <div class="statistic-icon avg-duration">
              <el-icon><Timer /></el-icon>
            </div>
            <div class="statistic-info">
              <div class="statistic-title">平均响应时间</div>
              <div class="statistic-value">
                {{ formatNumber(statistics.avg_duration_ms, 0) }} ms
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <div class="table-header">
        <div class="table-title">
          <el-icon><List /></el-icon>
          <span>模型调用记录列表</span>
        </div>
        <div class="table-actions">
          <el-button type="success" @click="exportData">
            <el-icon><Download /></el-icon> 导出数据
          </el-button>
        </div>
      </div>

      <el-table
        :data="tableData"
        style="width: 100%"
        border
        stripe
        v-loading="loading"
        :height="tableHeight"
      >
        <el-table-column prop="id" label="记录ID" width="100" :show-overflow-tooltip="true" />
        <el-table-column prop="user_id" label="用户ID" width="100" :show-overflow-tooltip="true" />
        <el-table-column prop="model_name" label="模型名称" width="150" />
        <el-table-column prop="tokens_total" label="总Token数" width="120" sortable />
        <el-table-column prop="tokens_prompt" label="提示Token" width="100" />
        <el-table-column prop="tokens_completion" label="完成Token" width="100" />
        <el-table-column prop="duration_ms" label="耗时(ms)" width="120" sortable />
        <el-table-column prop="prompt_content" label="提示词" :show-overflow-tooltip="true" />
        <el-table-column prop="status_code" label="状态码" width="80">
          <template #default="scope">
            <el-tag
              :type="scope.row.status_code === 200 ? 'success' : 'danger'"
              effect="plain"
              size="small"
            >
              {{ scope.row.status_code }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="调用时间" width="180" sortable />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              @click="viewLogDetail(scope.row)"
              class="detail-button"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.page_size"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="模型调用详情"
      width="70%"
      top="5vh"
      :destroy-on-close="true"
    >
      <div v-if="currentLog" class="detail-container">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="记录ID" label-align="right">{{
            currentLog.id
          }}</el-descriptions-item>
          <el-descriptions-item label="用户ID" label-align="right">{{
            currentLog.user_id
          }}</el-descriptions-item>
          <el-descriptions-item label="会话ID" label-align="right">{{
            currentLog.session_id
          }}</el-descriptions-item>
          <el-descriptions-item label="模型名称" label-align="right">{{
            currentLog.model_name
          }}</el-descriptions-item>

          <el-descriptions-item label="调用时间" label-align="right">{{
            currentLog.created_at
          }}</el-descriptions-item>
          <el-descriptions-item label="总Token数" label-align="right">{{
            currentLog.tokens_total
          }}</el-descriptions-item>
          <el-descriptions-item label="调用耗时" label-align="right"
            >{{ currentLog.duration_ms }} ms</el-descriptions-item
          >
          <el-descriptions-item label="请求ID" label-align="right">{{
            currentLog.request_id
          }}</el-descriptions-item>
          <el-descriptions-item label="状态码" label-align="right">
            <el-tag :type="currentLog.status_code === 200 ? 'success' : 'danger'">
              {{ currentLog.status_code }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <div class="prompt-content">
          <div class="content-title">提示词内容</div>
          <div class="content-area">
            <pre>{{ currentLog.prompt_content }}</pre>
          </div>
        </div>

        <div class="response-content">
          <div class="content-title">响应内容</div>
          <div class="content-area">
            <pre>{{ currentLog.response_content }}</pre>
          </div>
        </div>

        <div v-if="currentLog.error_message" class="error-message">
          <div class="content-title">错误信息</div>
          <div class="content-area error">
            <pre>{{ currentLog.error_message }}</pre>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import {
  Search,
  RefreshRight,
  Connection,
  DocumentChecked,
  Histogram,
  Timer,
  List,
  Download,
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getModelCallLogs, exportModelCallLogs } from '@/api/system'

defineOptions({
  name: 'ModelCallLogsPage',
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

// 状态变量
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const dateRange = ref([])
const modelOptions = ref([])
const statistics = ref({
  total_calls: 0,
  total_tokens: 0,
  avg_tokens: 0,
  avg_duration_ms: 0,
})
const dialogVisible = ref(false)
const currentLog = ref(null)

// 查询参数
const queryParams = reactive({
  page: 1,
  page_size: 10,
  start_date: '',
  end_date: '',
  model_name: '',
  user_id: '',
})

// 表格高度
const tableHeight = ref('calc(100vh - 450px)')

// 格式化数字
const formatNumber = (number, decimals = 0) => {
  if (number === undefined || number === null) return '0'
  return Number(number).toLocaleString('zh-CN', {
    minimumFractionDigits: decimals,
    maximumFractionDigits: decimals,
  })
}

// 处理日期范围变化
const handleDateRangeChange = (val) => {
  if (val) {
    queryParams.start_date = val[0]
    queryParams.end_date = val[1]
  } else {
    queryParams.start_date = ''
    queryParams.end_date = ''
  }
}

// 查询数据
const handleQuery = async () => {
  loading.value = true
  try {
    const response = await getModelCallLogs(queryParams)
    if (response.status) {
      tableData.value = response.data || []
      total.value = response.total || 0
      modelOptions.value = response.model_names || []
      statistics.value = {
        total_calls: response.stats.total_calls || 0,
        total_tokens: response.stats.total_tokens || 0,
        avg_tokens: response.stats.avg_tokens_per_call || 0,
        avg_duration_ms: response.stats.avg_duration_ms || 0,
      }
    } else {
      ElMessage.error('获取数据失败: ' + (response.message || '未知错误'))
    }
  } catch (error) {
    ElMessage.error('获取模型调用记录失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 重置查询
const resetQuery = () => {
  dateRange.value = []
  queryParams.page = 1
  queryParams.model_name = ''
  queryParams.user_id = ''
  queryParams.start_date = ''
  queryParams.end_date = ''
  handleQuery()
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.page_size = val
  handleQuery()
}

// 当前页变化
const handleCurrentChange = (val) => {
  queryParams.page = val
  handleQuery()
}

// 查看详情
const viewLogDetail = (row) => {
  currentLog.value = row
  dialogVisible.value = true
}

// 导出数据
const exportData = async () => {
  try {
    await ElMessageBox.confirm('确定要导出当前筛选条件下的所有记录吗？', '导出确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info',
    })

    loading.value = true

    // 调用导出API，这里假设您有导出API
    const response = await exportModelCallLogs({ ...queryParams, export: true })

    // 假设导出API返回下载链接或文件blob
    if (response.status === 'success' && response.download_url) {
      window.open(response.download_url, '_blank')
      ElMessage.success('导出成功，正在下载文件')
    } else if (response.file) {
      // 处理blob格式的文件下载
      const blob = new Blob([response.file], { type: 'application/vnd.ms-excel' })
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = `模型调用记录_${new Date().toISOString().slice(0, 10)}.xlsx`
      link.click()
      URL.revokeObjectURL(link.href)
      ElMessage.success('导出成功')
    } else {
      throw new Error('导出失败，未返回下载链接或文件')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('导出数据失败:', error)
      ElMessage.error('导出失败: ' + (error.message || '未知错误'))
    }
  } finally {
    loading.value = false
  }
}

// 初始化页面
onMounted(() => {
  handleQuery()

  // 动态调整表格高度
  const resizeTable = () => {
    nextTick(() => {
      tableHeight.value = `calc(100vh - 450px)`
    })
  }
  resizeTable()
  window.addEventListener('resize', resizeTable)
})
</script>

<style scoped>
.model-logs-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  height: calc(100vh - 120px);
  box-sizing: border-box;
}

.filter-card {
  width: 100%;
}

.filter-area {
  width: 100%;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  width: 100%;
}

.statistics-row {
  margin: 0;
}

.statistic-card {
  cursor: default;
  transition: all 0.3s;
}

.statistic-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.statistic-item {
  display: flex;
  align-items: center;
  padding: 10px;
}

.statistic-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.total-calls {
  background: linear-gradient(135deg, #1890ff, #36cfc9);
}

.total-tokens {
  background: linear-gradient(135deg, #52c41a, #73d13d);
}

.avg-tokens {
  background: linear-gradient(135deg, #722ed1, #9254de);
}

.avg-duration {
  background: linear-gradient(135deg, #fa8c16, #ffc53d);
}

.statistic-info {
  display: flex;
  flex-direction: column;
}

.statistic-title {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin-bottom: 8px;
}

.statistic-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--el-text-color-primary);
}

.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.table-title .el-icon {
  margin-right: 8px;
}

:deep(.el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-table) {
  flex: 1;
  overflow: auto;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.detail-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.content-title {
  font-weight: bold;
  margin-bottom: 8px;
  padding-left: 8px;
  border-left: 3px solid var(--el-color-primary);
}

.content-area {
  background-color: var(--el-fill-color-light);
  padding: 16px;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
}

.content-area pre {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-word;
}

.error {
  background-color: rgba(245, 108, 108, 0.1);
}

.detail-button {
  padding: 2px 0;
}

:global(.dark-mode) .content-area {
  background-color: rgba(255, 255, 255, 0.05);
}

:global(.dark-mode) .error {
  background-color: rgba(245, 108, 108, 0.2);
}
</style>
